import OpenAI from "openai";

function number_comparison(obj: { num1: number; num2: number }): number {
  if (obj.num1 > obj.num2) {
    return obj.num1;
  } else {
    return obj.num2;
  }
}

const openai = new OpenAI({
  baseURL: "http://127.0.0.1:11434/v1",
  apiKey: "",
});

async function sendLLm(
  messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[]
): Promise<OpenAI.Chat.Completions.ChatCompletionMessage> {
  const completion = await openai.chat.completions.create({
    model: "qwen2.5:32b",
    messages: messages,
    tools: [
      {
        type: "function",
        function: {
          name: "number_comparison",
          description: "比较两个数值谁更大，返回更大的值",
          parameters: {
            type: "object",
            properties: {
              num1: {
                type: "number",
              },
              num2: {
                type: "number",
                enum: ["celsius", "fahrenheit"],
              },
            },
            required: ["num1", "num2"],
          },
        },
      },
    ],
  });
  return completion.choices[0].message;
}

const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
  { role: "user", content: "9.9和9.11谁大" },
];

async function run() {
  const msg = await sendLLm(messages);
  messages.push(msg);
  if (msg.tool_calls) {
    msg.tool_calls.forEach(async (tool_call) => {
      if (tool_call.function.name === "number_comparison") {
        messages.push({
          tool_call_id: tool_call.id,
          role: "tool",
          // name: tool_call.function.name,
          content: number_comparison(JSON.parse(tool_call.function.arguments)).toString(),
        });
      }
    });
  }
  const ms2 = await sendLLm(messages);
  messages.push(ms2);
  console.log(messages);
}

run();
